#!coding:utf-8
'''
Created on Nov 8, 2012

@author: join
'''
from lottery_terminal.common import utils, Constant
import logging
import time
from lottery_terminal.models import Account, Period, Trade, TicketLoan
from lottery_terminal.service.lotteryservice.baseService import BaseLottery
import datetime
from lottery_terminal.common.ticketutil import pre_stop_dict, _ticket_obj
from lottery_terminal.service.lotteryservice.LoanLotteryService import LoanLottery
from lottery_terminal.service.lotteryservice.SSCLotteryService import SSCLottery
from lottery_terminal.service.lotteryservice.ThreaDLotteryService import ThreaDLottery
from lottery_terminal.service.lotteryservice.SixAndOneLotteryService import SixAndOneLottery
from lottery_terminal.service.lotteryservice.FifteenFiveLotteryService import FifteenFiveLottery
from lottery_terminal.service.lotteryservice.SevenColorLotteryService import SevenColorLottery
from lottery_terminal.rpc import rbc
from lottery_terminal.rpc.thrift_client import API

LOG = logging.getLogger('terminal')

lotterys=[u'01,02,03,04,05,06|01#1#1#1#2','01,02,03,04,05,06,07|01#1#2#1#14','01,02,03,04,05,06,07|01,02#1#2#1#28','01,02,03,04,05,06|01,02#1#2#1#4','01,02,03,04,05$06,07|01#1#5#1#4']
lotterycode='01'
mac='e5beb7f0e22d11ddb259000101000605'
#mac='000000000030'
    
@utils.ajaxrender
def chk_buy_lottery2(req):
    '''购买彩票前先检查是否为开奖时间，是否店主额度账户充足'''
#    lotterys = req.POST.getlist('lotterys[]')
#    lotterycode = req.POST.get('type')
#    mac = req.POST.get('mac')
    tradeamount = sum([int(t.split('#')[-1]) for t in lotterys])
    if tradeamount>20000:
        return u'购票失败,每次购买不能超过20000金额',400
    if not mac:
        return u'购票失败，机器无法识别',500
    start1 = time.time()
    LOG.info("****** query account1 start time:%s *********" % start1)
    tf_accounts = Account.objects.filter(deleted=False,accountType=2)
    LOG.info("****** total time:%s *********" % (time.time()-start1))
    if not tf_accounts:
        return u'尚未添加公司帐号',500
    if tf_accounts[0].balance<tradeamount:
        return u'彩票数量不足，请联系店主.',500
    
    start1 = time.time()
    LOG.info("****** query account1 start time:%s *********" % start1)      
    accounts = Account.objects.filter(deleted=False,mac=mac)
    LOG.info("****** total time:%s *********" % (time.time()-start1))
    if not accounts:
        return u'购票失败，机器无法识别',400
    baseLottery = BaseLottery(lotterycode)
    currenttime = datetime.datetime.now()+datetime.timedelta(minutes=pre_stop_dict.get(lotterycode),seconds=2)
    is_buy_time = baseLottery.is_buytime(currenttime)[0]
    if not is_buy_time:
        return u'当前时间为开奖时间',400   
    account = accounts[0]
    if account.balance<tradeamount:
        return u'店主余额不足，无法购票',400
    
@utils.ajaxrender
def buy_lottery2(req):
    '''购买彩票'''
#    lotterys = req.POST.getlist('lotterys[]')
#    lotterycode = req.POST.get('type')
#    mac = req.POST.get('mac')
    buymethod = '2' #购买方式，刷卡，投币或代购
    prizeType = 0 #现金:0,银联：1
    periodid = '2012133'
    
    if lotterycode == Constant.SSQ_CODE: #彩票代码为双色球
        service = LoanLottery()
    elif lotterycode == Constant.SSC_CODE: #彩票代码为时时彩
        service = SSCLottery()
    elif lotterycode == Constant.THREE_D_CODE: #彩票代码为福彩3D
        service = ThreaDLottery()
    elif lotterycode == Constant.SIX_ONE_CODE: #彩票代码为东方6+1
        service = SixAndOneLottery()
    elif lotterycode == Constant.FIFTEEN_FIVE_CODE: #彩票代码为15选5
        service = FifteenFiveLottery()
    elif lotterycode == Constant.QLC_CODE: #彩票代码为七乐彩
        service = SevenColorLottery()
            
    accounts = Account.objects.filter(deleted=False,mac=mac)
        
    tradeamount = sum([int(t.split('#')[-1]) for t in lotterys])
    if not mac:
        return u'购票失败，机器无法识别',500

#    if len(lotterys)>5:
#        return u'购票失败,每次不能超过5注',400
    start = time.time()
    periods = Period.objects.filter(lotterycode=lotterycode,periodid=periodid)
    end = time.time()
    diff = end-start
    if diff>0:
        LOG.error("####### Period.objects.filter:%s ##########"%diff)
    period = periods[0]
    
    
    end = time.time()
    diff = end-start
    if diff>0:
        LOG.error("####### Account.objects.filter:%s ##########"%diff)
        
#    ticketutil = TicketUtil(lotterycode)
    diff=time.time() -start
    if diff>0:
        LOG.error("is_buy_time:%s"%(time.time()-start))
        
    ticket_infos = {'period':period,'codes':lotterys,'buymethod':buymethod,'tradeAmount':tradeamount,
                        'account':accounts[0],'prizeType':prizeType}
    try:
        result = service.buy_ticket(ticket_infos)  #result格式目前是 msg,200
        LOG.error("service buy ticket:%s"%(time.time()-start))
    except Exception as e:
        LOG.exception('an exception occured:%s' % e)
        result = u'未知错误，购买彩票失败',500
    return result

@utils.ajaxrender
def test_rbc(req):
    print rbc.get_periods('01')
    return 'ok',200


@utils.ajaxrender
def test_thrift(req):
    API.get_periods('01')
    return 'ok',200

    
@utils.ajaxrender
def test_db(req):
    fuza_code = '01,02,03,04,05$06,07|01#1#5#1#4'
    periods = Period.objects.filter(lotterycode='01',periodid='2012133')
    accounts = Account.objects.filter(deleted=False,mac=mac)
    account = accounts[0]
    accounts2 = Account.objects.filter(deleted=False,accountType=2)
    tf_account = accounts2[0]
    trade = Trade(tradeType=1,tradeTicketType=1,tradeMethod=2,tradeAmount=12,period=periods[0],
                    accountid=account,tradeTime=utils.now(),status=2,prizeType=0,batchid='test20121110') #创建一条交易记录，状态为交易完成，如果失败再改回来
    trade.save()
    TicketLoan.objects.create(lotteryNumber=':'.join(fuza_code.split('#')[:-1]),ticketamount=1,buytime=utils.now(),
                          validitytime=utils.now(),status=2,buymoney=12,tradeId=trade,businessid='test1111')
    
    account.balance -= 12
    account.save()
    tf_account.balance-=12
    tf_account.save()
    return 'ok',200
